package vip.meeet.tool.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.time.Duration;
import java.time.Instant;

/**
 * https://github.com/cglib/cglib
 */
public class TimeingHelper {

    static class TimingIntercept implements MethodInterceptor{

        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            Instant start = Instant.now();
            Object result = methodProxy.invokeSuper(o, objects);
            Instant end = Instant.now();
            Duration timeElapse = Duration.between(start, end);
            System.out.println(timeElapse.toMillis());
            System.out.println(timeElapse.toString());
            System.out.println(timeElapse.toMinutes());
            return result;
        }
    }

    public static <T> T getTimingProxy(Class<T> clazz){
        Enhancer enhancer = new Enhancer();
        TimingIntercept timingIntercept = new TimingIntercept();
        enhancer.setCallback(timingIntercept);
        enhancer.setSuperclass(clazz);
        return (T) enhancer.create();
    }
}
